package com.lpf.streamAPI;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

import org.junit.Test;

import com.lpf.common.Employee;
import com.lpf.common.Status;


/**
 * 归约
 */
@SuppressWarnings("ALL")
public class StreamAPI_End_2 {

	List<Employee> employees = Arrays.asList(
			new Employee(102, "李四", 79, 6666.66, Status.BUSY),
			new Employee(101, "张三", 18, 9999.99, Status.FREE),
			new Employee(103, "王五", 28, 3333.33, Status.VOCATION),
			new Employee(104, "赵六", 8, 7777.77, Status.BUSY),
			new Employee(104, "赵六", 8, 7777.77, Status.FREE),
			new Employee(104, "赵六", 8, 7777.77, Status.FREE),
			new Employee(105, "田七", 38, 5555.55, Status.BUSY)
	);

	/**
	 * reduce(T identity, BinaryOperator)
	 * reduce(BinaryOperator) ——可以将流中元素反复结合起来，得到一个值。
	 */
	@Test
	public void testReduce() {
		List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);

		Integer sum = list.stream()
						  .reduce(0, Integer::sum);
		System.out.println(sum);

		System.out.println("----------------------------------------");

		Optional<Double> op = employees.stream()
			   					  .map(Employee::getSalary)
								  .reduce(Double::sum);
		System.out.println(op.get());
	}

	//需求：搜索名字中 “六” 出现的次数
	@Test
	public void test2() {
		Optional<Integer> sum = employees.stream()
									.map(Employee::getName)
									.flatMap(StreamAPI_End_2::filterCharacter)
									.map((ch) -> {
										if(ch.equals('六'))
											return 1;
										else
											return 0;
									})
									.reduce(Integer::sum);
		System.out.println(sum.get());
	}

	public static Stream<Character> filterCharacter(String str){
		List<Character> list = new ArrayList<>();
		for (Character ch : str.toCharArray()) {
			list.add(ch);
		}
		return list.stream();
	}
}
